<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>View Page</title>
    <script src="js/lib/vue.min.js"></script>
    <script src="js/lib/axios.min.js"></script>
</head>
<body>

<div id="app">

    <p><button type="button" @click="goToNewPage">go to new page</button></p>

    <p>file list :</p>

    <ul>
        <li v-for="file in files">
            <a href="#" @click="download(file.fileName)">{{file.fileName}}</a>
            <button type="button" @click="edit(file.fileId)">Edit</button>
        </li>
    </ul>

</div>

<script>
    var vm = new Vue({
        el: '#app',
        data: {
            files: []
        },
        methods: {
            goToNewPage: function(){
                window.location.href='new.html';
            },
            edit: function (fileId) {
                // 进入编辑页面的时候先尝试获得文件锁
                axios.get('/api/file/tryLock/' + fileId)
                .then(response => {
                    var data = response.data.data;
                    if (data.result) {
                        window.location.href='edit.html?fileId='+ fileId;
                    }else {
                        alert("文件已经被人锁住了！ TTL:[" + data.ttl + "] Holder:["+ data.holder +"]" )
                    }
                }).catch(error => {
                    alert(error);
                });
            },
            download: function (fileName) {
                // 调用文件下载接口
                axios.get('/api/file/download?fileName=' + fileName ,{
                    responseType: 'arraybuffer'
                })
                .then(response => {
                    // 主要为了解决跨域下载文件问题
                    let fileURL = window.URL.createObjectURL(new Blob([response.data]));
                    let fileLink = document.createElement('a');
                    fileLink.href = fileURL;
                    fileLink.setAttribute('download',fileName);
                    document.body.appendChild(fileLink);
                    fileLink.click();
                }).catch(error => {
                    alert(error);
                });
            }
        },
        mounted () {
            // 调用查找所有文件的接口
            axios.get('/api/file/list')
            .then(response => {
                // 返回文件列表
                var data = response.data.data;
                this.files = data;
            }).catch(error => {
                alert(error);
            });
        }
    })
</script>

</body>
</html>